#!/usr/bin/env bash

# Remove binaries.
__rvm_implode_binaries()
{
  # Load inside a subshell to avoid polutting the current shells env.
  (
    source "$rvm_scripts_path/base"

    rvm_log "Removing rvm-shipped binaries (rvm-prompt, rvm, rvm-sudo rvm-shell and rvm-auto-ruby)"
    for entry in "$rvm_bin_path/"{rvm-prompt,rvm,rvmsudo,rvm-shell,rvm-auto-ruby} ; do
      __rvm_rm_rf "$entry"
    done

    rvm_log "Removing rvm wrappers in $rvm_bin_path"
    __rvm_find "$rvm_bin_path" -type l | while read symlinked_rvm_file; do
      if [[ "$(__rvm_readlink "$symlinked_rvm_file")" == "$rvm_wrappers_path/"* ]]; then
        __rvm_rm_rf "$symlinked_rvm_file"
      fi
    done
    unset symlinked_rvm_file
  )
}

# Implode removes the entire rvm installation under $rvm_path, including removing wrappers.
__rvm_implode()
{
  if
    [[ ${rvm_force_flag:-0} -gt 0 ]] ||
    __rvm_ask_for "Are you SURE you wish for rvm to implode?\nThis will recursively remove $rvm_path and other rvm traces?" yes
  then
    if
      [[ "/" == "$rvm_path" ]]
    then
      rvm_error "remove '/' ?!... Ni!"
      return 1
    elif
      [[ -d "$rvm_path" ]]
    then
      __rvm_implode_binaries
      rvm_log "Hai! Removing $rvm_path"
      for file in /etc/profile.d/rvm.sh $rvm_man_path/man1/rvm.1* $rvm_path/
      do
        __rvm_rm_rf $file || rvm_error "Could not remove '$file', please try removing it manually."
      done

      if
        [[ -e $rvm_path ]]
      then
        rvm_warn "Failed to completely remove $rvm_path -- You will have to do so manually."
      else
        rvm_log "$rvm_path has been removed."
      fi

      if
        [[ "$rvm_path" == "/usr/local/rvm"* && -f "/usr/local/lib/rvm" ]]
      then
        rvm_log "Removing the rvm loader at /usr/local/lib/rvm"
        __rvm_rm_rf /usr/local/lib/rvm
      fi
      rvm_warn "
Note you may need to manually remove /etc/rvmrc and ~/.rvmrc if they exist still.
Please check all .bashrc .bash_profile .profile and .zshrc for RVM source lines and delete or comment out if this was a Per-User installation.
Also make sure to remove \`${rvm_group_name:-rvm}\` group if this was a system installation.
Finally it might help to relogin / restart if you want to have fresh environment (like for installing RVM again).
"
    else
      rvm_log "It appears that $rvm_path is already non existant."
    fi
  else
    rvm_log "Psychologist intervened, cancelling implosion, crisis avoided :)"
    return 2
  fi
}
